package com.example.demo.controller;

import com.example.demo.entity.Article;
import com.example.demo.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Controller
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @GetMapping("/article")
    public String all(Model model) {
        List<Article> articles = articleService.findAll();
        model.addAttribute("articles", articles);
        return "redirect:/article/1";
    }

    @GetMapping("/article/add")
    public String add() {
        return "add";
    }

    @PostMapping("/article/add")
    public String addArticle(@RequestParam("title") String title,@RequestParam("content") String content) {
        articleService.addArticle(title,content);
        return "redirect:/article/1";
    }

    @GetMapping("/article/update/{id}")
    public String update(Model model,@PathVariable("id") Integer id ) {
        Article article = articleService.findById(id);
        model.addAttribute("article", article);
        return "update";
    }

    @PostMapping("/article/update/{id}")
    public String updateArticle(@PathVariable("id") Integer id,@RequestParam Article article) {
//        articleService.updateArticle(id,title,content);
        article.setId(id);
        articleService.updateArticle(article);
        return "redirect:/article/1";
    }

    @GetMapping("/article/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        articleService.deleteArticleById(id);
        return "redirect:/article/1";
    }
    @GetMapping("/article/{page}")
    public String page(@PathVariable("page") int page, Model model) {
        Page<Article> articlePage = articleService.findAllByPage(page-1,2);
        int totalPages = articlePage.getTotalPages();
        List<Article> articles = articlePage.getContent();
        model.addAttribute("articles", articles);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("page", page);
        return "article";
    }
    @GetMapping("/index")
    public String index() {
        return "index";
    }
}
